var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Messages = require('../models/messages');

var mailer  = require('../util/mail');//邮件通知
var smsClient  = require('../util/smsClient');//短信通知

mongoose.connect('mongodb://127.0.0.1:27017/www');

mongoose.connection.on("connected", function() {
	console.log("success-------------")
})
mongoose.connection.on("error", function() {
	console.log("error")
})
mongoose.connection.on("disconnected", function() {
	console.log("disconnected")
})
//查询留言板列表数据
router.get("/list", function(req, res, next) {
	let pageNum = parseInt(req.param("pageNum"));
	let pageSize = parseInt(req.param("pageSize"));	
	let sort = -1;
	let skip = (pageNum-1)*pageSize;
	let params = {};
	let MessagesModel = Messages.find(params).skip(skip).limit(pageSize);
	MessagesModel.sort({'time':sort});
	MessagesModel.exec({}, function(err, doc) {
		if(err) {
			res.json({
				status: "0",
				msg: err.message
			})
		} else {
			res.json({
				status: "1",
				msg: "",
				result: {
					count: doc.length,
					list: doc
				}
			})
		}
	})
})
//添加留言
router.post("/add", function(req, res, next) {
	var data = {
		message: req.body.message,
		name: req.body.name,
	}
	Messages.find({}, function(err, doc) {
		if(err) {
			res.json({
				status: "0",
				msg: err.message
			})
		} else {
			if(doc) {
				data.id = doc.length + 1;
				data.time = new Date().getTime();
				Messages.create(data,function(err2, doc2) {
					if(err2) {
						res.json({
							status: "0",
							msg: err2.message
						})
					} else {
						res.json({
							status: "1",
							msg: "",
							result: "success"
						})
						//邮件通知
						mailer({
						    to: '1095406754@qq.com',
						    subject: data.name?"留言来自-"+data.name:"留言通知",
						    text: data.message
						});
						//短信通知
						smsClient(data.message)
					}
				})
			}
		}
	})
})
//删除留言
router.post("/del", function(req, res, next) {
	var id = req.body.id;
	Messages.remove({id:id},function(err,doc){
		if(err){
			res.json({
				status:"0",
				msg:err.message,
				result:""
			})
		}else{
			res.json({
				status:"1",
				msg:"",
				result:"success"
			})
		}
	})
})
module.exports = router;